package com.atguigu.gmall.search.config;

import com.atguigu.gmall.common.bean.PageParamVo;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.search.feign.GmallPmsClient;
import com.atguigu.gmall.search.feign.GmallWmsClient;
import com.atguigu.gmall.search.pojo.Goods;
import com.atguigu.gmall.search.pojo.SearchAttrValueVo;
import com.atguigu.gmall.search.repository.GoodsRepository;
import com.atguigu.gmall.search.service.SearchService;
import com.atguigu.gmall.wms.entity.WareSkuEntity;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mahaijun
 * @version 1.0.0
 * @ClassName ConsumerListener.java
 * @Description TODO
 * @createTime 2021年11月12日 18:22:00
 */
@Component
public class ConsumerListener {
    @Autowired
    private SearchService searchService;
    @Autowired
    private GmallPmsClient gmallPmsClient;
    @Autowired
    private GmallWmsClient gmallWmsClient;
    @Autowired
    private GoodsRepository goodsRepository;
    /**
     * 处理insert的消息
     *
//     * @param id
     * @throws Exception
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "item_spu_queue",durable = "true"),
            exchange = @Exchange(value = "item_exchange",
            ignoreDeclarationExceptions = "true",type = ExchangeTypes.TOPIC),
            key = {"item.insert"}
    ))
    public void listener(Long id ,Channel channel,Message message) throws IOException{
        if(id==null){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
//        ResponseVo<List<SpuEntity>> responseVo = this.gmallPmsClient.querySpuByPageJson(new PageParamVo(pageNum, pageSize, null));
        //3.遍历spu查询spu下的sku
//        List<SpuEntity> spuEntities = responseVo.getData();
//
//        if (!CollectionUtils.isEmpty(spuEntities)){
//
//
//        }
//        spuEntities.forEach(spuEntity -> {
        //根据spuid查询spu
        ResponseVo<SpuEntity> spuEntityResponseVo = this.gmallPmsClient.querySpuById(id);
        SpuEntity spuEntity = spuEntityResponseVo.getData();
        if(spuEntity==null){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        ResponseVo<List<SkuEntity>> skuResponseVo = this.gmallPmsClient.querySkuBySpuid(spuEntity.getId());
            List<SkuEntity> skuEntities = skuResponseVo.getData();

            if (!CollectionUtils.isEmpty(skuEntities)){
                //根据品牌的id查询品牌。同一个spu品牌是一样的，并且只有sku集合不为空时，才需要品牌
                ResponseVo<BrandEntity> brandEntityResponseVo = this.gmallPmsClient.queryBrandById(spuEntity.getBrandId());
                BrandEntity brandEntity = brandEntityResponseVo.getData();
                //根据分类的id查询分类。
                ResponseVo<CategoryEntity> categoryEntityResponseVo = this.gmallPmsClient.queryCategoryById(spuEntity.getCategoryId());
                CategoryEntity categoryEntity = categoryEntityResponseVo.getData();
                //根据分类Id 和spuid查询基本类型的规格参数和值
                ResponseVo<List<SpuAttrValueEntity>> spuAttrValueResponseVo = this.gmallPmsClient.querySearchAttrValueByCidAndSpuId(spuEntity.getCategoryId(), spuEntity.getId());
                List<SpuAttrValueEntity> spuAttrValueEntities = spuAttrValueResponseVo.getData();

                //4.把sku集合转成goods集合
                List<Goods> goodsList = skuEntities.stream().map(skuEntity -> {
                    Goods goods = new Goods();
                    //设置sku相关信息
                    goods.setSkuId(skuEntity.getId());
                    goods.setTitle(skuEntity.getTitle());
                    goods.setSubtitle(skuEntity.getSubtitle());
                    goods.setPrice(skuEntity.getPrice().doubleValue());
                    goods.setDefaultImage(skuEntity.getDefaultImage());
                    //设置排序分页及过滤参数
                    goods.setCreatTime(spuEntity.getCreateTime());
                    //库存查询
                    ResponseVo<List<WareSkuEntity>> wareSkuResponseVo = this.gmallWmsClient.queryWareSkuBySkuId(skuEntity.getId());
                    List<WareSkuEntity> wareSkuEntities = wareSkuResponseVo.getData();
                    if (!CollectionUtils.isEmpty(wareSkuEntities)){
                        goods.setSales(wareSkuEntities.stream().map(WareSkuEntity::getSales).reduce((a, b) -> a + b).get());
                        goods.setStore(wareSkuEntities.stream().anyMatch(wareSkuEntity -> wareSkuEntity.getStock()-wareSkuEntity.getStockLocked()>0));
                    }
                    //品牌
                    if (brandEntity != null){
                        goods.setBrandId(brandEntity.getId());
                        goods.setBrandName(brandEntity.getName());
                        goods.setLogo(brandEntity.getLogo());
                    }
                    //分类
                    if (categoryEntity != null){
                        goods.setCategoryId(categoryEntity.getId());
                        goods.setCategoryName(categoryEntity.getName());
                    }
                    //销售参数
                    List<SearchAttrValueVo> searchAttrValues = new ArrayList<>();
                    //销售类型
                    ResponseVo<List<SkuAttrValueEntity>> skuAttrValueResponseVo = this.gmallPmsClient.querySearchAttrValueByCidAndSkuId(skuEntity.getCategoryId(), skuEntity.getId());
                    List<SkuAttrValueEntity> skuAttrValueEntities = skuAttrValueResponseVo.getData();
                    if (!CollectionUtils.isEmpty(skuAttrValueEntities)){
                        searchAttrValues.addAll(skuAttrValueEntities.stream().map(skuAttrValueEntity -> {
                            SearchAttrValueVo searchAttrValue = new SearchAttrValueVo();
                            BeanUtils.copyProperties(skuAttrValueEntity,searchAttrValue);
                            return searchAttrValue;
                        }).collect(Collectors.toList()));

                    }
                    //基本类型的规格参数p
                    if (!CollectionUtils.isEmpty(spuAttrValueEntities)){
                        searchAttrValues.addAll(spuAttrValueEntities.stream().map(spuAttrValueEntity -> {
                            SearchAttrValueVo searchAttrValue = new SearchAttrValueVo();
                            BeanUtils.copyProperties(spuAttrValueEntity,searchAttrValue);
                            return searchAttrValue;
                        }).collect(Collectors.toList()));

                    }

                    goods.setSearchAttrs(searchAttrValues);



                    return goods;
                }).collect(Collectors.toList());

                //5.批量保存到索引库

                this.goodsRepository.saveAll(goodsList);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//        try {
//            System.out.println(msg);
//            //手动确认消息
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//        } catch (IOException e) {
//            e.printStackTrace();
//            //是否已经重试过
//            if(message.getMessageProperties().getRedelivered()){
//                //已重试过直接拒绝
//                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
//
//            }else{
//                //未重试过，重新入队
//                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
//            }
//        }


    }

}
